<template>
  <el-dialog
    :title="title"
    :width="width"
    :visible="visible"
    @close="visible = false"
  >
    <el-row :gutter="24">
      <el-col :span="2" :offset="21">
        <el-button
          type="primary"
          @click="downloadCurrentPage('CodeArea')"
        >下载当前页</el-button>
      </el-col>
    </el-row>
    <el-row id="CodeArea" :gutter="24">
      <el-col v-for="(item, index) in QrData" :key="index" :span="4">
        <div class="qr-box">
          <qr-code :text="item.QrString" :size="190" :margin="10" />
          <div style="text-align: center;">
            {{ item.QrName ? item.QrName : "---" }}
          </div>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import qrCode from 'vue-qr'
import Canvas2Image from '@/utils/canvas2Image.js'
import html2canvas from 'html2canvas'
export default {
  name: 'BatchQRCode',
  components: {
    qrCode
  },
  props: {
    title: {
      type: String,
      default: '二维码'
    },
    width: {
      type: String,
      default: '80%'
    }
  },
  data() {
    return {
      visible: false,
      qrString: '123',
      QrData: [],
      imgName: '二维码'
    }
  },
  methods: {
    downloadCurrentPage(elementId) {
      const that = this
      // 生成图片之前，需先将整体的滚动条隐藏掉，否则生成出来的照片会偏移
      document.getElementById('app').style.overflowY = 'hidden'
      // 两个参数：所需要截图的元素id，截图后要执行的函数， canvas为截图后返回的最后一个canvas
      var shareContent = document.getElementById(elementId)
      var width = shareContent.offsetWidth
      var height = shareContent.offsetHeight
      var canvas = document.createElement('canvas')
      var scale = 6 // 这里为了下载出更清晰的图片，值越大越清晰

      canvas.width = width * scale
      canvas.height = height * scale
      canvas.getContext('2d').scale(scale, scale)

      var opts = {
        scale: 1, // 不管上面的scale是多少倍，这里只能取1，否则会显示不完全
        canvas: canvas,
        logging: true,
        width: width,
        height: height
      }
      html2canvas(shareContent, opts).then(function(canvas) {
        // 这个方式是直接将canvas保存为图片的，具体参数可自行查看源码
        // eslint-disable-next-line no-unused-vars
        var img = Canvas2Image.saveAsImage(
          canvas,
          canvas.width,
          canvas.height,
          'png',
          that.imgName
        )
        // 这个方式只是提供展示图片的功能，暂时没有用到
        // var img = Canvas2Image.convertToPNG(canvas, canvas.width, canvas.height,'PNG');
        //  document.body.appendChild(img);

        // 生成图片之前，需先将整体的滚动恢复为之前的状态
        document.getElementById('app').style.overflowY = 'scroll'
        // 关闭loading
      })
    },
    /**
     * 打开批量二维码弹窗
     * @param {Array} QrData 二维码数据
     * @param {String} imgName 下载时文件名
     */
    open(QrData, imgName) {
      this.imgName = imgName
      this.QrData = QrData
      this.visible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-box {
  border: 1px solid black;
  margin: 5px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
